package com.fosu.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.fosu.common.ResponseResult;
import com.fosu.dao.FeedbackDao;
import com.fosu.dao.FeedbackImgDao;
import com.fosu.domain.Feedback;
import com.fosu.service.FeedbackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName FeedbackServiceImpl
 * @Description 反馈业务实现类
 * @Author 夜天冥
 * @Date 2020/11/14 21:24
 * @Version 1.0
 */
@Service
@Transactional
public class FeedbackServiceImpl implements FeedbackService {
    @Autowired
    private FeedbackDao feedbackDao;

    @Autowired
    private FeedbackImgDao feedbackImgDao;

    Feedback feedback = null;
    //从json获取imgsUrl数组
    JSONArray imgsArray = null;

    @Override
    public ResponseResult findAllFeedback(HttpServletResponse resp) {
        return ResponseResult.ok(resp,"获取反馈列表成功",feedbackDao.findAllFeedback());
    }

    @Override
    public ResponseResult save(HttpServletResponse resp, JSONObject jsonPram) throws Exception {
        try {
            //从json获取imgsUrl数组
            imgsArray = jsonPram.getJSONArray("productImgsUrl");

            //保存feedback数据到数据库
            try {
                feedback = jsonPram.getObject("feedback",Feedback.class);
                feedbackDao.saveFeedback(feedback);
            }catch (JSONException e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResponseResult.fail(resp,"反馈发布失败");
            }

            int feedbackId = feedback.getFeedbackId();

            //保存imgsUrl到数据库 并与feedback的关系到数据库
            for (int i = 0; i < imgsArray.size(); i++){
                feedbackImgDao.save(feedbackId,imgsArray.getString(i));
            }
            return ResponseResult.ok(resp,"反馈发布成功");
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

            return ResponseResult.fail(resp,"反馈发布失败");
        }

    }
}
